package timbap.visualizer.api.plugin.recorditems;

import timbap.visualizer.api.model.RecordItem;
import timbap.visualizer.api.model.Transformation;
import timbap.visualizer.api.plugin.AbstractPlugin;

/**
 * The <code>AbstractRecordItemsPlugin</code> provides a common base
 * implementation of the <code>RecordItemsPlugin</code> interface that
 * should be used by record item drawing plugins.
 *
 * It provides an implementation of the <code>draw()</code> method
 * that applies a record-item-specific transformation of the coordinate
 * system and delegates the drawing of every record item for which
 * visualization is necessary to the unimplemented
 * <code>drawRecordItem(RecordItem)</code> method.
 *
 * @author  Andreas Pabst
 * @see     timbap.visualizer.api.model.RecordItem
 * @see     timbap.visualizer.api.plugin.recorditems.RecordItemsPlugin
 * @see     timbap.visualizer.api.plugin.AbstractPlugin
 */
public abstract class AbstractRecordItemsPlugin extends AbstractPlugin implements RecordItemsPlugin {

	public void draw() {
		
		for (RecordItem tRecordItem: getContext().getRecordItemManager().getRecordItems()) {
            if (isVisualizationNecessary(tRecordItem)) {
                getContext().getP5Applet().pushMatrix();
                applyRecordTrafo(tRecordItem);
                drawRecordItem(tRecordItem);
                getContext().getP5Applet().popMatrix();
            }
        }
		
	}
	
	/**
	 * applies the transformation of a given record item
	 * 
	 * @param pRecordItem	the record item to get the applied transformation from
	 */
	protected void applyRecordTrafo(RecordItem pRecordItem) {
	    applyRecordTrafo(pRecordItem, 1.0f);
	}

	/**
	 * applies the transformation of a given record item with
	 * a given scale factor to the rendering pipeline.
	 * 
	 * @param pRecordItem	the record item to get the applied transformation from
	 * @param pScaleFactor	the scale factor to apply
	 */
	protected void applyRecordTrafo(RecordItem pRecordItem, float pScaleFactor) {
    	
    	Transformation tItemTrafo = pRecordItem.getTransformation();
        
    	getContext().getP5Applet().translate(
                                tItemTrafo.getXTranslation() * pScaleFactor,
    							tItemTrafo.getYTranslation() * pScaleFactor,
    							tItemTrafo.getZTranslation());
    	getContext().getP5Applet().scale(tItemTrafo.getScaleFactor() * pScaleFactor);
    	getContext().getP5Applet().rotate(tItemTrafo.getRotation());
    	getContext().getP5Applet().rotateX(tItemTrafo.getXRotation());
        
    }
    
}
